<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" size="small">
        <el-form-item label="学号" prop="studentNo">
          <el-input
            v-model="queryParams.studentNo"
            placeholder="请输入学号"
            clearable
            prefix-icon="el-icon-user"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="填报年份" prop="entranceYear">
          <el-date-picker
            v-model="queryParams.entranceYear"
            type="year"
            placeholder="选择年份"
            value-format="yyyy"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input
            v-model="queryParams.studentName"
            placeholder="请输入学生姓名"
            clearable
            prefix-icon="el-icon-notebook-2"
            style="width: 180px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['entrance:aspiration:add']"
        >填报志愿</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['entrance:aspiration:export']"
          :loading="exportLoading"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格展示区域 -->
    <el-card shadow="hover" class="table-card">
      <el-table 
        v-loading="loading" 
        :data="aspirationList"
        border
        stripe
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="ID" prop="id" width="70" align="center"/>
        <el-table-column label="学生姓名" prop="studentName" min-width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.studentName || '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学号" prop="studentNo" min-width="120" :show-overflow-tooltip="true"/>
        <el-table-column label="填报年份" prop="entranceYear" width="90" align="center"/>
        <el-table-column label="志愿状态" width="110" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              <i :class="getStatusIcon(scope.row.status)" style="margin-right: 3px;"></i> 
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createdTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope" v-if="scope.row.id !== 0">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDetail(scope.row)"
            >详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['entrance:aspiration:edit']"
            >修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 详情弹框 -->
    <el-dialog
      title="志愿填报详情"
      :visible.sync="dialogVisible"
      width="600px"
      class="aspiration-dialog"
    >
      <div v-if="aspirationDetail">
        <el-descriptions title="学生信息" :column="2" border>
          <el-descriptions-item label="学生姓名">{{ aspirationDetail.studentName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ aspirationDetail.studentNo }}</el-descriptions-item>
          <el-descriptions-item label="填报年份">{{ aspirationDetail.entranceYear }}</el-descriptions-item>
          <el-descriptions-item label="填报时间">{{ parseTime(aspirationDetail.createdTime) }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-title">志愿信息</div>
        <el-steps :active="3" finish-status="success" simple style="margin: 20px 0">
          <el-step title="第一志愿"></el-step>
          <el-step title="第二志愿"></el-step>
          <el-step title="第三志愿"></el-step>
        </el-steps>
        
        <el-card shadow="never" class="aspiration-item" v-if="aspirationDetail.college1">
          <div slot="header">
            <span>第一志愿</span>
            <el-tag type="success" size="small" style="margin-left: 10px">首选</el-tag>
          </div>
          <div class="aspiration-content">
            <div class="college-name">{{ aspirationDetail.college1 }}</div>
            <div class="major-name">{{ aspirationDetail.profession1 }}</div>
          </div>
        </el-card>
        
        <el-card shadow="never" class="aspiration-item" v-if="aspirationDetail.college2">
          <div slot="header">
            <span>第二志愿</span>
          </div>
          <div class="aspiration-content">
            <div class="college-name">{{ aspirationDetail.college2 }}</div>
            <div class="major-name">{{ aspirationDetail.profession2 }}</div>
          </div>
        </el-card>
        
        <el-card shadow="never" class="aspiration-item" v-if="aspirationDetail.college3">
          <div slot="header">
            <span>第三志愿</span>
          </div>
          <div class="aspiration-content">
            <div class="college-name">{{ aspirationDetail.college3 }}</div>
            <div class="major-name">{{ aspirationDetail.profession3 }}</div>
          </div>
        </el-card>
      </div>
      <div v-else class="empty-detail">
        <i class="el-icon-document"></i>
        <p>暂无详细信息</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { aspirationDetail, listAspiration } from "@/api/entrance/aspiration";
import { listStudent } from "@/api/entrance/student"; // 使用学生列表API替代单个学生查询

export default {
  name: "Aspiration",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 志愿表格数据
      aspirationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentNo: undefined,
        studentName: undefined,
        entranceYear: undefined
      },
      // 表单参数
      form: {},
      dialogVisible: false,
      aspirationDetail: null,
      // --- 添加模拟详情数据占位符 ---
      mockDetailData: {
        studentName: "张三",
        studentNo: "A20230001",
        entranceYear: "2024",
        createdTime: new Date().toISOString(),
        college1: "清华大学",
        profession1: "计算机科学与技术",
        college2: "北京大学",
        profession2: "金融学",
        college3: "浙江大学",
        profession3: "人工智能",
        status: 1
      },
      // --- 模拟数据结束 ---
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 学生信息缓存
      studentCache: {},
      // 选中数组ids
      selectedIds: [], // 用于存储选中的ID
      // 选中行数据
      selectedRows: [], // 用于存储选中的行数据
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询志愿列表 */
    getList() {
      this.loading = true;
      listAspiration(this.queryParams).then(
        response => {
          this.aspirationList = response.rows;
          // 处理学生姓名显示
          this.processStudentNames();
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    
    /** 处理学生姓名显示 */
    processStudentNames() {
      // 获取所有需要查询学生信息的学号
      const studentNos = this.aspirationList
        .filter(item => item.studentNo && (!item.studentName || item.studentName === ''))
        .map(item => item.studentNo);
      
      if (studentNos.length > 0) {
        // 使用列表查询API进行批量查询
        this.queryStudentNames(studentNos);
      }
    },
    
    /** 批量查询学生姓名 */
    queryStudentNames(studentNos) {
      // 使用学生列表API，通过学号模糊查询获取学生信息
      listStudent({ studentNos: studentNos.join(',') }).then(res => {
        if (res.code === 200 && res.rows) {
          // 创建学号到学生名字的映射
          const studentMap = {};
          res.rows.forEach(student => {
            studentMap[student.studentNo] = student;
            // 更新缓存
            this.studentCache[student.studentNo] = student;
          });
          
          // 更新列表中的学生姓名
          this.aspirationList = this.aspirationList.map(item => {
            if (studentMap[item.studentNo]) {
              return {
                ...item,
                studentName: studentMap[item.studentNo].studentName || '未知'
              };
            }
            return item;
          });
        }
      }).catch(() => {
        // 查询失败时不做特殊处理
      });
    },
    
    /** 详情按钮操作 */
    handleDetail(row) {
      const studentNo = row.studentNo;
      // --- 使用模拟数据 --- 
      this.aspirationDetail = { 
        ...this.mockDetailData, 
        studentName: row.studentName || this.mockDetailData.studentName, // 尝试使用列表中的名字
        studentNo: studentNo // 使用当前行的学号
      };
      this.dialogVisible = true;
      // --- 模拟数据结束 ---
      
      // --- 原 API 调用逻辑 (注释掉) ---
      // this.aspirationDetail = null; // 清空旧数据
      // this.dialogVisible = true;
      // aspirationDetail(studentNo).then(response => {
      //   if (response.code === 200) {
      //     this.aspirationDetail = response.data;
      //     // 如果需要，合并学生信息 (如果 detail API 不返回学生姓名)
      //     if (!this.aspirationDetail.studentName && row.studentName) {
      //       this.$set(this.aspirationDetail, 'studentName', row.studentName);
      //     }
      //   } else {
      //     this.$message.error(response.msg || "获取详情失败");
      //     this.dialogVisible = false; // 获取失败则不显示弹窗
      //   }
      // }).catch(() => {
      //   this.$message.error("请求详情异常");
      //   this.dialogVisible = false;
      // });
      // --- 原 API 调用逻辑结束 ---
    },
    
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: '/entrance/aspiration/form' });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({ 
        path: '/entrance/aspiration/form',
        query: { studentNo: row.studentNo }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.exportLoading = true;
      // 这里假设有导出API，实际需要根据项目情况实现
      setTimeout(() => {
        this.$message.success("导出成功");
        this.exportLoading = false;
      }, 1000);
    },
    /** 获取状态文本 */
    getStatusText(status) {
      if (status === 1) return '已确认';
      if (status === 0) return '待确认';
      return '未填报';
    },
    /** 获取状态类型 */
    getStatusType(status) {
      if (status === 1) return 'success';
      if (status === 0) return 'warning';
      return 'info';
    },
    /** 获取状态图标 */
    getStatusIcon(status) {
      if (status === 1) return 'el-icon-success';
      if (status === 0) return 'el-icon-question';
      return 'el-icon-info';
    },
    /** 处理表格 checkbox 选择 */
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
      this.selectedRows = selection;
      // 更新按钮禁用状态 (如果需要批量操作)
      // this.single = selection.length!==1
      // this.multiple = !selection.length
    },
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .mb8 {
    margin-bottom: 15px;
  }
  
  .aspiration-dialog {
    .detail-title {
      font-size: 16px;
      font-weight: 600;
      margin: 20px 0 10px;
      padding-left: 10px;
      border-left: 3px solid #409EFF;
    }
    
    .aspiration-item {
      margin-bottom: 15px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .aspiration-content {
        display: flex;
        flex-direction: column;
        
        .college-name {
          font-size: 16px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 5px;
        }
        
        .major-name {
          color: #606266;
        }
      }
    }
    
    .empty-detail {
      text-align: center;
      padding: 30px 0;
      color: #909399;
      
      i {
        font-size: 48px;
        margin-bottom: 10px;
      }
      
      p {
        font-size: 16px;
      }
    }
  }
}
</style>
